<template>
  <div class="expend-container">
    <h2>开销列表</h2>

    <div class="toolbar">
      <el-button type="primary" @click="addItem">添加项目</el-button>
      <el-button type="success" style="margin-left: 10px;" @click="saveDataToLocal">保存数据</el-button>
      <el-button type="warning" style="margin-left: 10px;" @click="loadDataFromLocal">加载数据</el-button>
      <el-button type="danger" style="margin-left: 10px;" @click="clearLocalData">清空本地数据</el-button>
    </div>

    <el-table :data="expendItems" style="width: 100%" border>
      <el-table-column prop="name" label="项目名称" />
      <el-table-column prop="amount" label="金额">
        <template #default="scope">
          ¥{{ scope.row.amount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="是否参与计算" width="120">
        <template #default="scope">
          <el-switch v-model="scope.row.includeInCalc" @change="recalculate" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="editItem(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteItem(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="summary">
      <div class="summary-item">
        <span>月合计:</span>
        <strong class="expend">¥{{ monthlyTotal.toFixed(2) }}</strong>
      </div>
      <div class="summary-item">
        <span>年合计:</span>
        <strong class="expend">¥{{ yearlyTotal.toFixed(2) }}</strong>
      </div>
    </div>

    <!-- 其它支出 -->
    <div class="other-expenses">
      <h3>其它支出</h3>

      <div class="toolbar">
        <el-button type="primary" @click="addOtherItem">添加其它支出</el-button>
      </div>

      <el-table :data="otherExpendItems" style="width: 100%" border>
        <el-table-column prop="name" label="项目名称" />
        <el-table-column prop="amount" label="金额">
          <template #default="scope">
            ¥{{ scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="是否参与计算" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.includeInCalc" @change="recalculate" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="editOtherItem(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteOtherItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="summary">
        <div class="summary-item">
          <span>其它支出合计:</span>
          <strong class="expend">¥{{ otherTotal.toFixed(2) }}</strong>
        </div>
      </div>
    </div>

    <!-- 收入项 -->
    <div class="income-section">
      <h3>收入列表</h3>

      <div class="toolbar">
        <el-button type="primary" @click="addIncomeItem">添加收入</el-button>
      </div>

      <el-table :data="incomeItems" style="width: 100%" border>
        <el-table-column prop="name" label="项目名称" />
        <el-table-column prop="amount" label="金额">
          <template #default="scope">
            ¥{{ scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="是否参与计算" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.includeInCalc" @change="recalculate" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="editIncomeItem(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteIncomeItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="summary">
        <div class="summary-item">
          <span>月收入合计:</span>
          <strong class="income">¥{{ monthlyIncomeTotal.toFixed(2) }}</strong>
        </div>
        <div class="summary-item">
          <span>年收入合计:</span>
          <strong class="income">¥{{ yearlyIncomeTotal.toFixed(2) }}</strong>
        </div>
      </div>
    </div>

    <!-- 其它收入 -->
    <div class="other-income">
      <h3>其它收入</h3>

      <div class="toolbar">
        <el-button type="primary" @click="addOtherIncomeItem">添加其它收入</el-button>
      </div>

      <el-table :data="otherIncomeItems" style="width: 100%" border>
        <el-table-column prop="name" label="项目名称" />
        <el-table-column prop="amount" label="金额">
          <template #default="scope">
            ¥{{ scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="是否参与计算" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.includeInCalc" @change="recalculate" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="editOtherIncomeItem(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteOtherIncomeItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="summary">
        <div class="summary-item">
          <span>其它收入合计:</span>
          <strong class="income">¥{{ otherIncomeTotal.toFixed(2) }}</strong>
        </div>
      </div>
    </div>

    <!-- 总计 -->
    <div class="summary overall-summary">
      <div class="summary-item years-control">
        <span>年数:</span>
        <el-input-number v-model="years" :min="1" :max="100" size="small" />
      </div>
      <div class="summary-item">
        <span>{{ years }}年开销:</span>
        <strong class="expend">¥{{ (yearlyTotal * years).toFixed(2) }}</strong>
      </div>
      <div class="summary-item">
        <span>其它支出:</span>
        <strong class="expend">¥{{ otherTotal.toFixed(2) }}</strong>
      </div>
      <div class="summary-item">
        <span>{{ years }}年收入:</span>
        <strong class="income">¥{{ (yearlyIncomeTotal * years).toFixed(2) }}</strong>
      </div>
      <div class="summary-item">
        <span>其它收入:</span>
        <strong class="income">¥{{ otherIncomeTotal.toFixed(2) }}</strong>
      </div>
      <div class="summary-item">
        <span>总合计:</span>
        <strong :class="{ negative: totalBalance < 0, positive: totalBalance >= 0 }">
          ¥{{ totalBalance.toFixed(2) }}
        </strong>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="400px">
      <el-form :model="form" label-width="80px">
        <el-form-item label="项目名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="金额">
          <el-input-number v-model="form.amount" :precision="2" :step="1" controls-position="right" />
        </el-form-item>
        <el-form-item label="类别">
          <el-select v-model="form.type" placeholder="请选择类别">
            <el-option label="主要支出" value="main"/>
            <el-option label="其它支出" value="other"/>
            <el-option label="主要收入" value="income"/>
            <el-option label="其它收入" value="otherIncome"/>
          </el-select>
        </el-form-item>
        <el-form-item label="参与计算">
          <el-switch v-model="form.includeInCalc" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveItem">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { ref, reactive, computed, onMounted } from 'vue'

// 开销项
const expendItems = ref([
  { name: '房贷', amount: 4200, includeInCalc: true },
  { name: '水电', amount: 40, includeInCalc: true },
  { name: '物业费', amount: 260, includeInCalc: true },
  { name: '油费', amount: 400, includeInCalc: true },
  { name: '停车费', amount: 350, includeInCalc: true },
  { name: '吃饭', amount: 4000, includeInCalc: true },
  { name: '购物', amount: 1000, includeInCalc: true },
  { name: '孩子', amount: 3000, includeInCalc: true }
])

// 其它开销项
const otherExpendItems = ref([
  { name: '三金', amount: 60000, includeInCalc: true },
  { name: '酒席', amount: 60000, includeInCalc: true },
  { name: '婚纱照', amount: 10000, includeInCalc: true },
  { name: '父亲/母亲节', amount: 2000, includeInCalc: true },
  { name: '父亲/母亲生日', amount: 2000, includeInCalc: true },
  { name: '首付', amount: 300000, includeInCalc: true },
  { name: '装修', amount: 180000, includeInCalc: true },
  { name: '家具', amount: 30000, includeInCalc: true },
  { name: '家电', amount: 40000, includeInCalc: true },
  { name: '第一次见家长', amount: 2000, includeInCalc: true },
  { name: '订婚', amount: 4000, includeInCalc: true }
])

// 收入项
const incomeItems = ref([
  { name: '工资', amount: 13000, includeInCalc: true }
])

// 其它收入项
const otherIncomeItems = ref([
  { name: '借债', amount: 41500, includeInCalc: true },
  { name: '基金/股票', amount: 114252, includeInCalc: true },
  { name: '储蓄卡', amount: 12414, includeInCalc: true },
  { name: '微信/支付宝', amount: 6184, includeInCalc: true }
])

const years = ref(1) // 默认年数为1年

const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEditing = ref(false)
const editIndex = ref(-1)
const editingType = ref('') // 'main', 'other', 'income' 或 'otherIncome'

const form = reactive({
  name: '',
  amount: 0,
  type: 'main',
  includeInCalc: true
})

// 支出计算
const monthlyTotal = computed(() => {
  return expendItems.value
    .filter(item => item.includeInCalc)
    .reduce((total, item) => total + item.amount, 0)
})

const yearlyTotal = computed(() => {
  return monthlyTotal.value * 12
})

const otherTotal = computed(() => {
  return otherExpendItems.value
    .filter(item => item.includeInCalc)
    .reduce((total, item) => total + item.amount, 0)
})

// 收入计算
const monthlyIncomeTotal = computed(() => {
  return incomeItems.value
    .filter(item => item.includeInCalc)
    .reduce((total, item) => total + item.amount, 0)
})

const yearlyIncomeTotal = computed(() => {
  return monthlyIncomeTotal.value * 12
})

const otherIncomeTotal = computed(() => {
  return otherIncomeItems.value
    .filter(item => item.includeInCalc)
    .reduce((total, item) => total + item.amount, 0)
})

// 总余额计算 (收入 - 支出)
const totalBalance = computed(() => {
  const totalExpend = (yearlyTotal.value * years.value) + otherTotal.value
  const totalIncome = (yearlyIncomeTotal.value * years.value) + otherIncomeTotal.value
  return totalIncome - totalExpend
})

// 重新计算方法
const recalculate = () => {
  // 触发重新计算
  // 因为使用了computed属性，改变includeInCalc会自动触发重新计算
}

// 保存数据到本地存储
const saveDataToLocal = () => {
  try {
    const data = {
      expendItems: expendItems.value,
      otherExpendItems: otherExpendItems.value,
      incomeItems: incomeItems.value,
      otherIncomeItems: otherIncomeItems.value,
      years: years.value
    }
    localStorage.setItem('expendData', JSON.stringify(data))
    ElMessage.success('数据已保存到本地')
  } catch (error) {
    ElMessage.error(`保存失败：${error.message}`)
  }
}

// 从本地存储加载数据
const loadDataFromLocal = () => {
  try {
    const data = localStorage.getItem('expendData')
    if (data) {
      const parsedData = JSON.parse(data)
      expendItems.value = parsedData.expendItems || []
      otherExpendItems.value = parsedData.otherExpendItems || []
      incomeItems.value = parsedData.incomeItems || []
      otherIncomeItems.value = parsedData.otherIncomeItems || []
      years.value = parsedData.years || 1
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.warning('没有找到本地保存的数据')
    }
  } catch (error) {
    ElMessage.error(`加载失败：${error.message}`)
  }
}

// 清空本地存储的数据
const clearLocalData = () => {
  try {
    localStorage.removeItem('expendData')
    ElMessage.success('本地数据已清空')
  } catch (error) {
    ElMessage.error(`清空失败：${error.message}`)
  }
}

// 页面加载时尝试从本地存储恢复数据
onMounted(() => {
  loadDataFromLocal()
})

// 支出操作
const addItem = () => {
  dialogTitle.value = '添加项目'
  isEditing.value = false
  form.name = ''
  form.amount = 0
  form.type = 'main'
  form.includeInCalc = true
  dialogVisible.value = true
}

const addOtherItem = () => {
  dialogTitle.value = '添加其它支出'
  isEditing.value = false
  form.name = ''
  form.amount = 0
  form.type = 'other'
  form.includeInCalc = true
  dialogVisible.value = true
}

const editItem = (item) => {
  dialogTitle.value = '编辑项目'
  isEditing.value = true
  editingType.value = 'main'
  editIndex.value = expendItems.value.indexOf(item)
  form.name = item.name
  form.amount = item.amount
  form.type = 'main'
  form.includeInCalc = item.includeInCalc
  dialogVisible.value = true
}

const editOtherItem = (item) => {
  dialogTitle.value = '编辑其它支出'
  isEditing.value = true
  editingType.value = 'other'
  editIndex.value = otherExpendItems.value.indexOf(item)
  form.name = item.name
  form.amount = item.amount
  form.type = 'other'
  form.includeInCalc = item.includeInCalc
  dialogVisible.value = true
}

const deleteItem = (index) => {
  expendItems.value.splice(index, 1)
}

const deleteOtherItem = (index) => {
  otherExpendItems.value.splice(index, 1)
}

// 收入操作
const addIncomeItem = () => {
  dialogTitle.value = '添加收入'
  isEditing.value = false
  form.name = ''
  form.amount = 0
  form.type = 'income'
  form.includeInCalc = true
  dialogVisible.value = true
}

const addOtherIncomeItem = () => {
  dialogTitle.value = '添加其它收入'
  isEditing.value = false
  form.name = ''
  form.amount = 0
  form.type = 'otherIncome'
  form.includeInCalc = true
  dialogVisible.value = true
}

const editIncomeItem = (item) => {
  dialogTitle.value = '编辑收入'
  isEditing.value = true
  editingType.value = 'income'
  editIndex.value = incomeItems.value.indexOf(item)
  form.name = item.name
  form.amount = item.amount
  form.type = 'income'
  form.includeInCalc = item.includeInCalc
  dialogVisible.value = true
}

const editOtherIncomeItem = (item) => {
  dialogTitle.value = '编辑其它收入'
  isEditing.value = true
  editingType.value = 'otherIncome'
  editIndex.value = otherIncomeItems.value.indexOf(item)
  form.name = item.name
  form.amount = item.amount
  form.type = 'otherIncome'
  form.includeInCalc = item.includeInCalc
  dialogVisible.value = true
}

const deleteIncomeItem = (index) => {
  incomeItems.value.splice(index, 1)
}

const deleteOtherIncomeItem = (index) => {
  otherIncomeItems.value.splice(index, 1)
}

const saveItem = () => {
  if (isEditing.value) {
    if (editingType.value === 'main') {
      expendItems.value[editIndex.value] = {
        name: form.name,
        amount: form.amount,
        includeInCalc: form.includeInCalc
      }
    } else if (editingType.value === 'other') {
      otherExpendItems.value[editIndex.value] = {
        name: form.name,
        amount: form.amount,
        includeInCalc: form.includeInCalc
      }
    } else if (editingType.value === 'income') {
      incomeItems.value[editIndex.value] = {
        name: form.name,
        amount: form.amount,
        includeInCalc: form.includeInCalc
      }
    } else if (editingType.value === 'otherIncome') {
      otherIncomeItems.value[editIndex.value] = {
        name: form.name,
        amount: form.amount,
        includeInCalc: form.includeInCalc
      }
    }
  } else {
    if (form.type === 'main') {
      expendItems.value.push({
        name: form.name,
        amount: form.amount,
        includeInCalc: form.includeInCalc
      })
    } else if (form.type === 'other') {
      otherExpendItems.value.push({
        name: form.name,
        amount: form.amount,
        includeInCalc: form.includeInCalc
      })
    } else if (form.type === 'income') {
      incomeItems.value.push({
        name: form.name,
        amount: form.amount,
        includeInCalc: form.includeInCalc
      })
    } else if (form.type === 'otherIncome') {
      otherIncomeItems.value.push({
        name: form.name,
        amount: form.amount,
        includeInCalc: form.includeInCalc
      })
    }
  }
  dialogVisible.value = false
}
</script>

<style scoped>
.expend-container {
  overflow: auto;
  padding: 20px;
  margin: 0 auto;
  max-width: 1100px;
  height: 100%;
}

.toolbar {
  margin-bottom: 20px;
  text-align: right;
}

.summary {
  padding: 20px 0;
}

.summary-item {
  margin-bottom: 20px;
  font-size: 16px;
  text-align: right;
}

.summary-item strong {
  margin-left: 10px;
}

.summary-item strong.expend {
  color: #67c23a; /* 柔和的绿色 */
}

.summary-item strong.income {
  color: #f56c6c; /* 柔和的红色 */
}

.summary-item strong.negative {
  color: #67c23a; /* 负数显示柔和的绿色 */
}

.summary-item strong.positive {
  color: #f56c6c; /* 正数显示柔和的红色 */
}

.summary-item.years-control {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.summary-item.years-control span {
  margin-right: 10px;
}

.overall-summary {
  border-top: 1px solid #eee;
}
</style>
